﻿using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Xml;

namespace Spot.ContentLibrary.Extensibility 
{
    [DataContract]
    public class PropertiesBag
    {
        IDictionary<string, object> _properties;
        public PropertiesBag()
        {
            _properties = new Dictionary<string, object>();
        }

        public void Add(string key, object value)
        {
            _properties[key] = value;
        }

        public PropertiesBag Merge(string prefix, PropertiesBag propertiesBag)
        {
            foreach (var property in propertiesBag.Properties)
            {
                Add(string.Format("{0}.{1}", prefix, property.Key), property.Value);
            }
            return this;
        }
        public PropertiesBag Merge(PropertiesBag propertiesBag)
        {
            foreach (var property in propertiesBag.Properties)
            {
                Add(property.Key, property.Value);
            }
            return this;
        }


        public PropertiesBag GetPrefixedProperties(string prefix)
        {
            var propertiesBag = new PropertiesBag();
            foreach (var property in _properties.Where(property => property.Key.StartsWith(prefix + ".")))
            {
                propertiesBag.Add(property.Key.Substring(prefix.Length+1), property.Value);
            }
            return propertiesBag;
        }

        public T TryGetOrDefault<T>(string key, T defaultValue)
        {
            if (_properties.ContainsKey(key))
            {
                var val = _properties[key];
                if (val is T)
                {
                    return (T)val;
                }
            }
            return defaultValue;
        }

        [DataMember]
        internal IDictionary<string, object> Properties
        {
            get { return _properties; }
            set { _properties = value; }
        }
    }


    public static class PropertiesBagExt
    {
        public static XmlDocument XmlSerialize(this PropertiesBag desc)
        {
            var serializer = new Serialization.ContentLibrarySerializer(); 
            return serializer.XmlSerialize(desc);
        }
    }
}
